package com.gopay.cashier.common.util.qrcode;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by liyang on 2017/8/10.
 * 生成二维码工具类
 */
public class QRCodeUtil {

    private static final Logger log = LoggerFactory.getLogger(QRCodeUtil.class);

    /**
     * 默认是黑色
     */
    private static final int QRCOLOR = 0xFF000000;

    /**
     * 背景颜色
     */
    private static final int BGWHITE = 0xFFFFFFFF;

    public static String createQRCode(String qrUlr, Map<String, Integer> size) {
        String img = "";
        try {
            img = getLogoQRCode(qrUlr, "", size.get("width"), size.get("height"));
        } catch (Exception e) {
            log.info("生成二维码失败" + e);
        }
        return img;
    }


    /**
     * 生成带logo的二维码图片
     *
     * @param qrUrl
     * @param productName
     */
    private static String getLogoQRCode(String qrUrl, String productName, int width, int height) {
        String content = qrUrl;
        try {
            QRCodeUtil zp = new QRCodeUtil();
            BufferedImage bim = zp.getQR_CODEBufferedImage(content, BarcodeFormat.QR_CODE, width, height, zp.getDecodeHintType());
            return zp.addLogo_QRCode(bim);
        } catch (Exception e) {
            log.error("生成带logo的二维码图片异常：" + e);
        }
        return null;
    }

    /**
     * 没有logo的二维码
     *
     * @param bim
     * @param bim
     */
    private String addLogo_QRCode(BufferedImage bim) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            baos.flush();
            ImageIO.write(bim, "png", baos);
            String imageBase64QRCode = Base64.encodeBase64String(baos.toByteArray());
            baos.close();
            return imageBase64QRCode;
        } catch (Exception e) {
            log.error("生成没有logo的二维码异常：" + e);
        }
        return null;
    }

    /**
     * 构建初始化二维码
     *
     * @param bm
     * @return
     */
    private BufferedImage fileToBufferedImage(BitMatrix bm) {
        BufferedImage image = null;
        try {
            int w = bm.getWidth(), h = bm.getHeight();
            image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

            for (int x = 0; x < w; x++) {
                for (int y = 0; y < h; y++) {
                    image.setRGB(x, y, bm.get(x, y) ? 0xFF000000 : 0xFFCCDDEE);
                }
            }
        } catch (Exception e) {
            log.error("初始化二维码异常：" + e);
        }
        return image;
    }

    /**
     * 生成二维码bufferedImage图片
     *
     * @param content       编码内容
     * @param barcodeFormat 编码类型
     * @param width         图片宽度
     * @param height        图片高度
     * @param hints         设置参数
     * @return
     */
    private BufferedImage getQR_CODEBufferedImage(String content, BarcodeFormat barcodeFormat, int width, int height, Map<EncodeHintType, ?> hints) {
        MultiFormatWriter multiFormatWriter = null;
        BitMatrix bm = null;
        BufferedImage image = null;
        try {
            multiFormatWriter = new MultiFormatWriter();
            // 参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
            bm = multiFormatWriter.encode(content, barcodeFormat, width, height, hints);
            int w = bm.getWidth();
            int h = bm.getHeight();
            image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

            // 开始利用二维码数据创建Bitmap图片，分别设为黑（0xFFFFFFFF）白（0xFF000000）两色
            for (int x = 0; x < w; x++) {
                for (int y = 0; y < h; y++) {
                    image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
                }
            }
        } catch (WriterException e) {
            log.error("生成二维码异常：" + e);
        }
        return image;
    }

    /**
     * 设置二维码的格式参数
     *
     * @return Map
     */
    private Map<EncodeHintType, Object> getDecodeHintType() {
        // 用于设置QR二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        // 设置QR二维码的纠错级别（H为最高级别）具体级别信息
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 设置编码方式
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN, 0);
        hints.put(EncodeHintType.MAX_SIZE, 350);
        hints.put(EncodeHintType.MIN_SIZE, 100);
        return hints;
    }
}
